package com.ss.tools;

import com.ss.tools.file.FileType;
import com.ss.tools.file.FileTypeJudge;
import org.apache.commons.codec.binary.Base64;
import org.springframework.util.StringUtils;


public class Base64ImageUtils {

    public static boolean isCheckBase64(String base64Data) {
        boolean state = true;
        try {
            byte[] imgByte = Base64.decodeBase64(base64Data.replaceAll(" ", "+"));
            String rtype = FileTypeJudge.getType(imgByte).toString();
            if (StringUtils.isEmpty(rtype)) {
                state = false;
            }
        } catch (Exception e) {
            state = false;
        }
        return state;
    }


    public static String getBase64FileType(String base64Data, String... types) {
        try {
            byte[] imgByte = Base64.decodeBase64(base64Data.replaceAll(" ", "+"));
            FileType rtype = FileTypeJudge.getType(imgByte);
            if (rtype == null) {
                return null;
            }
            String type = rtype.toString().toLowerCase();
            if (types == null || types.length == 0) {
                return type;
            }
            for (String t : types) {
                if (t != null) {

                    if (t.toLowerCase().equals(type))
                        return type;
                }
            }
        } catch (Exception exception) {
        }

        return null;
    }


    public static boolean isCheckBase64(String base64Data, String... types) {
        String type = getBase64FileType(base64Data, types);
        if (StringUtils.isEmpty(type)) {
            return false;
        }
        return true;
    }

}
